package the.broccoli.weixin.service;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Service;
import the.broccoli.weixin.service.support.SubscribeSupport;
import the.broccoli.weixin.service.support.UnsubscribeSupport;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service
@Slf4j
public class WeiXinMpService {

    @Resource
    private WxMpService wxMpService;

    @Resource
    private SubscribeSupport subscribeSupport;

    @Resource
    private UnsubscribeSupport unsubscribeSupport;

    private WxMpMessageRouter router;

    @PostConstruct
    public void init() {
        this.refreshRouter();
    }

    public void refreshRouter() {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(
                this.wxMpService);
        // 记录所有事件的日志
        //newRouter.rule().handler(this.logHandler).next();
        // 关注事件
        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.SUBSCRIBE).handler(this.subscribeSupport)
                .end();
        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.UNSUBSCRIBE).handler(this.unsubscribeSupport)
                .end();
        // 默认,转发消息给客服人员
        //newRouter.rule().async(false).handler(this.msgHandler).end();
        this.router = newRouter;
    }

    public WxMpXmlOutMessage route(WxMpXmlMessage inMessage) {
        try {
            return this.router.route(inMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }


}
